/**
 * Created by lx on 2018/4/3.
 */
CommonUtils.regNamespace("com.im.projectInfoManage.itemSubmitManage");

$(function() {
    com.im.projectInfoManage.itemSubmitManage.invoke.init();
});

com.im.projectInfoManage.itemSubmitManage.invoke = function() {
    var client = new com.im.common.ajax();
    var tmpfiles;//文件上传下载

    /**
     * 页面初始化
     * @private
     */
    function _init() {
        //初始化时间、复选框、下拉框等事件和样式
        _initCommpentAction();
        //获取规划类型列表
        $("#vPlanTypesSelect").constantCommpent({
    	    elmIdSel : "vPlanTypesSelect",//需要展示的位置下拉框
    	    constParamCode : "PLAN_PROJ_CLASS",//需要加载的常量编码
    	    callbackFunc: function (objvalue, objname) {//下拉框值改变时回调
    	    	_querySubjects(1);
    	    }
    	});
        //获取项目阶段类型列表
        _queryPhases();
        //获取项目状态类型列表
        _queryStates();
        //获取项目进度类型列表
        //_queryProgresses();
        //查询项目进度列表
        $("#vSubjectsBtn").on("click", function () {
            _querySubjects(1);
        }).trigger("click");
        //修改项目阶段
        $("#vSubmitSubject").on("click", _editSubject);
        //条件重置
        $("#vResetCond").on("click", _resetCond);
        //问题与建议数字限制
        $('#vJy').keyup(function(){
        	var len = $(this).val().length;
        	if(len > 100){
        	    $(this).val($(this).val().substring(0,100));
            	toastr.error('问题和建议字数不能超哥100字！');
        	}
        });
    }

    function _initCommpentAction() {
        //时间插件
        $('#startDatepicker').datepicker({
            autoclose: true,
        }).on('changeDate',function () {
            $('#addEditProjectForm').data('bootstrapValidator').updateStatus('startDatepicker', 'NOT_VALIDATED',null).validateField('startDatepicker');
            $('#addEditProjectForm').data('bootstrapValidator').updateStatus('endDatepicker', 'NOT_VALIDATED',null).validateField('endDatepicker');
        });
        $('#endDatepicker').datepicker({
            autoclose: true,
        }).on('changeDate',function () {
            $('#addEditProjectForm').data('bootstrapValidator').updateStatus('endDatepicker', 'NOT_VALIDATED',null).validateField('endDatepicker');
        });

        //复选框
        $('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
            checkboxClass: 'icheckbox_minimal-blue',
            radioClass   : 'iradio_minimal-blue'
        });

        //下拉框
        $('.select2').select2();

        //建设单位查询组件
        $("#vCompanyNameInput").unitselCommpent({
            elmIdSel : "vCompanyNameInput",//需要展示的位置下拉框
            unitType : "10",//单位类型 为空的时候全部查询
            callbackFunc: function (objvalue, objname) {//下拉框值改变时回调
            	_querySubjects(1);
            }
        });
    }

    /**
     * 获取项目阶段类型列表
     * @private
     */
    function _queryPhases(){
        var req = {};
        var resp = client.callAsJson("projectInfoService/queryProjStageConstList", req);
        if (!resp.success) {
            toastr.error(resp.resultMsg);
            return;
        }

//        var vPhases = $("#vPhases");
//        $.each(resp.result.rows, function (i, item) {
//            if(i == 0) {
//                vPhases.append("<option vaPhaseId='" + item.paramValValue + "' selected='selected'>" + item.paramValName + "</option>");
//            } else {
//                vPhases.append("<option vaPhaseId='" + item.paramValValue + "'>" + item.paramValName + "</option>");
//            }
//        });
    }

    /**
     * 获取项目状态类型列表
     * @private
     */
    function _queryStates(){
        var req = {};
        req.tabName = "T_PROJ_PROCE_SUBMIT";
        req.colName ="STATUS_CD";
        var resp = client.callAsJson("commonService/queryTabColParam", req);
        if (!resp.success) {
            toastr.error(resp.resultMsg);
            return;
        }

//        var vStates = $("#vStates");
//        $.each(resp.result, function (i, item) {
//            if(i == 0) {
//                vStates.append("<option vaStateId='" + item.colVal + "' selected='selected'>" + item.colValName + "</option>");
//            } else {
//                vStates.append("<option vaStateId='" + item.colVal + "'>" + item.colValName + "</option>");
//            }
//        });
    }

    /**
     * 获取项目进度类型列表
     * @private
     */
    function _queryProgresses(){
        var req = {};
        var resp = client.callAsJson("获取项目进度类型列表", req);
        resp.success = true;
        resp.result = [{"mProgressId":"10", "mProgressName":"进度1-模拟"},{"mProgressId":"20", "mProgressName":"进度2-模拟"}];
        if (!resp.success) {
            toastr.error(resp.resultMsg);
            return;
        }

//        var vProgresses = $("#vProgresses");
//        $.each(resp.result, function (i, item) {
//            if(i == 0) {
//                vProgresses.append("<option vaProgressId='" + item.mProgressId + "' selected='selected'>" + item.mProgressName + "</option>");
//            } else {
//                vProgresses.append("<option vaProgressId='" + item.mProgressId + "'>" + item.mProgressName + "</option>");
//            }
//        });
    }

    /**
     * 获取规划类型列表
     * @private
     */
    function _queryPlanTypes() {
        var req = {};
        var resp = client.callAsJson("projectInfoService/queryPlanProjClassConstList", req);
        if (!resp.success) {
            toastr.error(resp.resultMsg);
            return;
        }

        //规划类型列表添加元素
        var vPlanTypesSelect = $("#vPlanTypesSelect");
        $.each(resp.result, function (i, item) {
            if(i == 0) {
                vPlanTypesSelect.append("<option vaPlanTypeId='" + item.paramValValue + "' selected='selected'>" + item.paramValName + "</option>");
            } else {
                vPlanTypesSelect.append("<option vaPlanTypeId='" + item.paramValValue + "'>" + item.paramValName + "</option>");
            }
        });
    }

    /**
     * 查询项目进度列表
     * @param index
     * @param needTurn
     * @private
     */
    function _querySubjects(index) {
        if(com.im.projectInfoManage.itemSubmitManage.subjectColumns == undefined) {
            com.im.projectInfoManage.itemSubmitManage.subjectColumns = [[
                	{field:'vaSeq',title:"序<br/>号",width:30,rowspan:2,fitColumns:true,formatter: function(value,row,index){return (index+1);}},
                    {field:'planProjName',title:"工程名称",width:100,rowspan:2,align:'left',fitColumns:true},
                    {field:'impleProjName',title:"实施项目名称",width:100,rowspan:2,align:'left',fitColumns:true,},
                    {field:'developOrgName',title:"建设单位",width:80,rowspan:2,align:'left',fitColumns:true},
                    {title:"建设年限",colspan:2,fitColumns:true},
                    {field:'leadingPersonName',title:"项目<br/>负责人",width:60,rowspan:2,fitColumns:true},
                    {field:'linkmanName',title:"项目<br/>联系人",width:60,rowspan:2,fitColumns:true},
                    {title:"阶段资金构成（单位：万元）",colspan:6,fitColumns:true},
                    {field:'preWorkSituation',title:"前期工作情况",width:100,rowspan:2,align:'left',fitColumns:true,formatter: function(value,row,index){
                    	if(value){
                            return value.replace(/;/g,'<br/>');
                    	}else{
                    		return '';
                    	}
                    }},
	                {field:'impleSituation',title:"最新进度",width:120,rowspan:2,fitColumns:true},
	                {field:'enterDt',title:"填报时间",width:100,rowspan:2,fitColumns:true},
	                {field:'suggest',title:"问题和建议",width:120,align:'left',rowspan:2,fitColumns:true,
//	                	formatter: function(value,row,index) {
//		                    if (value.length > 10) {
//		                        return value.substr(0, 10);
//		                    } else {
//		                        return value;
//		                    }
//	                	}
	                },
                    {field:'fileList',title:"提交的附件",rowspan:2,width:100,fitColumns:true,align:'left',formatter: function(value,row,index){
                        if(value.length > 0){
                            var fileNames = "";
                            $.each(value, function (i, item) {
                                fileNames += item.attachFullName + "  ";
                            });
                            return fileNames;
                        }else {
                            return "";
                        }
                    }},
                {field:'vaOperation',title:"操作",width:80,rowspan:2,fitColumns:true,formatter: function(value,row,index){return  "<a href='javascript:;' onclick='com.im.projectInfoManage.itemSubmitManage.invoke.showEditSubject(" + index + ")' title='修改'><i class='fa fa-edit'></i></a>";}}
            ],[{field:'startDt',title:"开工年",fitColumns:true},
                {field:'endDt',title:"完工年",fitColumns:true},
                {field:'total',title:"合计",fitColumns:true},
                {field:'fundSourceBu',title:"部补助",fitColumns:true},
                {field:'fundSourceSheng',title:"省财政",fitColumns:true},
                {field:'fundSourceGao',title:"政府融资",fitColumns:true},
                {field:'fundSourceShi',title:"市州配套",fitColumns:true},
                {field:'fundSourceQi',title:"企业自筹",fitColumns:true}]];
        }

        var req = {};
        req.pageInfo = {};
        req.pageInfo.pageNumber = index;
        req.pageInfo.pageSize = 20;
        req.operation = 'query';
        req.planProjClass = $("#vPlanTypesSelect option:selected").attr("value");
        req.planProjName = $("#vProjectNameInput").val();
        req.impleProjName = $("#vSubjectNameInput").val();
        var developOrg = $("#vCompanyNameInput option:selected").attr("value");
        if(developOrg != ''){
        	req.developOrg = developOrg;
        }else{
        	delete req.developOrg;
        }

        var resp = client.callAsJson("projectInfoService/queryProjProceSubmitList", req);
        if (!resp.success) {
            toastr.error(resp.resultMsg);
            return;
        } else {

        }

        plans = resp.result.rows;
        $("#vSubjectTable").empty();
        $("#vSubjectTable").datagrid({
    	    nowrap:false,
    	    fitColumns:true,
        	pagination:true,
        	columns:com.im.projectInfoManage.itemSubmitManage.subjectColumns,
        	data:resp.result
        });
        var p = $('#vSubjectTable').datagrid('getPager');
        $(p).pagination({
            total : resp.result.total,
            pageSize : resp.result.pageSize,
            pageNumber : resp.result.pageNumber,
            pageList : [20 , 40],
            beforePageText: '第',
            afterPageText: '页    共 {pages}  页',
            displayMsg: '当前显示 {from} - {to} 条记录 共 {total}  条记录',
            onSelectPage:function(pageNumber, pageSize){
                _querySubjects(pageNumber);
            }
        });
    }

    function _showEditSubject(index) {
        var row = $('#vSubjectTable').datagrid('getData').rows[index];
        //文件
        var fileList = row.fileList;
        $.each(fileList,function (index,item){
            fileList[index].fileSuffix = item.attachFullName;
            fileList[index].uploadName = item.attachFullName;
            fileList[index].filePath = item.attachPath;
            fileList[index].uploadId = item.uploadId;
        });
        var file = new com.im.common.file();
        tmpfiles = file.activate(1,fileList);

        $("#vSubjectId").val(row.impleProjId);
        $("#vSubjectName").val(row.impleProjName);
        $("#vPlanName").val();
        $("#vProjectName").val(row.planProjName);
        $("#vCompanyName").val(row.developOrgName);
        $("#vStartDt").val(row.startDt);
        $("#vEndDt").val(row.endDt);
        $("#vFzrName").val(row.leadingPersonName);
        $("#vLxdhName").val(row.linkmanName);
        $("#vProgresses").val(com.im.common.util.descapeTextArea(row.impleSituation));
//        $("#vPhases").val(row.projStageClassName).trigger("change");
//        $("#vStates").val(row.statusName).trigger("change");
        $("#vJy").val(com.im.common.util.descapeTextArea(row.suggest));

        $("#addEditModal").modal("show");
    }

    /**
     * 修改项目阶段
     * @private
     */
    function _editSubject() {
        var req = {};
        req.impleProjId = $("#vSubjectId").val();
//        req.statusCd = Number($("#vStates option:selected").attr("vaStateId"));
//        req.projStageClass = $("#vPhases option:selected").attr("vaPhaseId");
        req.impleSituation = $("#vProgresses").val();
        req.suggest = com.im.common.util.escapeTextArea($("#vJy").val());
        client.callAsFile(tmpfiles.newly, function(fileRes) {
            if(fileRes.success){
                req.addFileList = fileRes.result;
                req.delFileList = tmpfiles.del;
                var resp = client.callAsJson("projectInfoService/updateProjProceSubmit", req);
                if (!resp.success) {
                    toastr.error(resp.resultMsg);
                    return;
                } else {
                    toastr.success("修改项目阶段成功");
                }
            }else{
                toastr.error('文件服务器忙！请稍后再试！');
            }

            _querySubjects(1);
            $("#addEditModal").modal("hide");
        });
    }

    /**
     * 条件重置
     * @private
     */
    function _resetCond() {
        $("#vCompanyNameInput").val("").trigger("change");
        $("#vPlanTypesSelect").find("option:selected").removeAttr("selected");
        $("#vPlanTypesSelect").find("option").first().attr("selected", "selected");
        $("#vPlanTypesSelect").trigger("change");
        $("#vProjectNameInput").val("");
        $("#vSubjectNameInput").val("");
        _querySubjects(1);//重复调用
    }

    return {
        init : _init,
        showEditSubject : _showEditSubject
    }
}();